import axios from 'axios'
import store from '../store'
import router from '../router/index'
import { Message } from 'element-ui'
import Setting from '../..//setting'
// 创建axios实例
const request2 = axios.create({
  baseURL: Setting.apiBaseUrl,
  // baseURL:'http://192.168.43.99:10527',
  // baseURL: 'http://192.168.43.99:10527',
  timeout: 15000
})

request2.interceptors.request.use(
  function (config) {
    // const token = 'cd43b6f7-5d6b-4ccb-94a9-6027b1d63989'
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    const token = store.state.token || localStorage.getItem('nanxun_token')
    if (token) {
      config.headers.Authorization = `${token}`
    }
    config.headers['Sys-Type'] = '1'
    // 在发送请求之前做些什么
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request2.interceptors.response.use(async function (response) {
  // 默认json格式
  // 在每次响应数据返回的时候解构
  const { msg, status } = response

  if (status === 200) {
    return response
  } else {
    if (status == 401) {
      Message.error(response.data.msg)
      await store.commit('delToken')
      router.push('/login')
    } else {
      Message.error(msg)
      return Promise.reject(response.data)
    }
  }
})

// 导出axios实例
export default request2
